package cq.zhcqk.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONObject;

import cq.zhcqk.R;
import cq.zhcqk.util.AsyncHttpClientUtils;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.SpUtil;
import cq.zhcqk.util.StringUtil;
import cq.zhcqk.util.ToastUtil;
import cq.zhcqk.widget.RegisterCodeTimer;

/**
 * Created by zhangle on 2018/3/19.
 */
public class RegisterActivityNew extends AppCompatActivity implements View.OnClickListener {
    private Button register_next;
    private EditText register_phone;
    private ImageView header_back;
    private EditText code;
    private EditText password;
    private TextView tv_getcode;
    private AsyncHttpClient httpClient;
    private Context context;
    private BuildBean buildBean;
    protected SharedPreferences mSharedPreferences;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        context = this;
        httpClient = AsyncHttpClientUtils.getInstance().getAsyncHttpClient();
        mSharedPreferences = SpUtil.getSpBykey(context, SpUtil.TOKEN);
        initView();
        initBack();
    }
    private void initView(){
        buildBean = DialogUIUtils.showLoading(this, "加载中...", true, true, true, false);
        register_next = (Button) findViewById(R.id.register_next);
        register_phone = (EditText) findViewById(R.id.register_phone);
        header_back = (ImageView) findViewById(R.id.header_back);
        code = (EditText) findViewById(R.id.code);
        password = (EditText) findViewById(R.id.password);
        tv_getcode = (TextView) findViewById(R.id.tv_getcode);

        tv_getcode.setOnClickListener(this);
        register_next.setOnClickListener(this);
        header_back.setOnClickListener(this);
    }

    private void initBack(){
        ImageView back = (ImageView) findViewById(R.id.header_back);
        TextView title = (TextView) findViewById(R.id.header_text);
        title.setText("注册");
        back.setOnClickListener(this);
    }
    String phoneNo = null;
    @Override
    public void onClick(View v) {

        Intent intent = null;
        switch (v.getId()){
            case R.id.register_next:
                String phoneNo1 = register_phone.getText()+"";
                if ("".equals(phoneNo1)){
                    ToastUtil.showToast(context,"请输入手机号码");
                    break;
                }
                String codeTxt = code.getText()+"";
                String passwordTxt = password.getText()+"";
                if ("".equals(codeTxt)){
                    ToastUtil.showToast(context,"请输入验证码");
                    break;
                }
                if ("".equals(passwordTxt)){
                    ToastUtil.showToast(context,"请输入密码");
                    break;
                }
                register(phoneNo,passwordTxt,codeTxt);
                break;
            case R.id.tv_getcode:
                phoneNo = register_phone.getText()+"";
                if ("".equals(phoneNo)){
                    ToastUtil.showToast(context,"请输入手机号码");
                    break;
                }
                RegisterCodeTimer codeTimer = new RegisterCodeTimer(tv_getcode, R.string.register_getMsgCode_validate,
                        R.color.black_text, R.color.white);
                codeTimer.start();
                getCode(phoneNo);
                break;
            case R.id.header_back:
                finish();
                break;
        }
    }

    private void getCode(String phoneNo){
        RequestParams params = new RequestParams();
        params.add("phone",phoneNo);
        buildBean.show();
        httpClient.post(Common.URL+Common.GET_CODE,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"发送失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("errorResponse："+responseString);
                Toast.makeText(context,"发送失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    private void register(final String phone, final String pwd, String cd){
        RequestParams params = new RequestParams();
        params.add("phone",phone);
        params.add("password",pwd);
        params.add("code",cd);
        buildBean.show();
        httpClient.post(Common.URL+Common.REGISTER,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Toast.makeText(context,"注册成功",Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = mSharedPreferences.edit();
                editor.putString("phone",phone);
                editor.putString("password",pwd);
                editor.commit();
                startActivity(new Intent(context,LoginActivity.class));
                finish();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                String failMsg = StringUtil.getFailMsg(errorResponse);
                if(failMsg != null){
                    Toast.makeText(context,failMsg,Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(context,"注册失败，请稍后再试",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Toast.makeText(context,"注册失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }
}
